package io.polly.ldz.reactor.security;



import io.polly.ldz.reactor.enums.RoleEnum;
import io.polly.ldz.reactor.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;


import java.util.ArrayList;


/**
 * @version 3.5.0
 * @description: 登录用户名密码验证
 * Copyright (C), 2020-2021,
 * @date 2021/12/25 9:45
 */
@Component
@Slf4j
public class RestAuthenticationProvider implements AuthenticationProvider {

    private final UserService userService;


    private final ApplicationEventPublisher eventPublisher;


    /**
     * Instantiates a new Rest authentication provider.
     *
     * @param userService           the user service
     */
    @Autowired
    public RestAuthenticationProvider(UserService userService, ApplicationEventPublisher eventPublisher) {

        this.userService = userService;
        this.eventPublisher = eventPublisher;

    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();

        DigestWebAuthenticationDetails details = (DigestWebAuthenticationDetails)authentication.getDetails();

        io.polly.ldz.reactor.entity.User user = userService.getUserByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        boolean result = true;
        if (!result) {
            throw new BadCredentialsException("用户名或密码错误");
        }

        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        grantedAuthorities.add(new SimpleGrantedAuthority(RoleEnum.fromCode(user.getRole()).getRoleName()));

        User authUser = new User(user.getUserName(), user.getPassword(), grantedAuthorities);

        return new UsernamePasswordAuthenticationToken(authUser, authUser.getPassword(), authUser.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
